package com.zm.campus.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zm.campus.dao.*;
import com.zm.campus.pojo.*;
import com.zm.campus.query.ReplaceDoQuery;
import com.zm.campus.service.IReplaceDoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zm.campus.util.AssertUtil;
import com.zm.campus.util.SnowflakeIdGenerator;
import com.zm.campus.vo.AuditListVo;
import com.zm.campus.vo.LoginReturnVo;
import com.zm.campus.vo.ReplaceDoReturnVo;
import com.zm.campus.vo.RepublishRDVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zm
 */
@Service
public class ReplaceDoServiceImpl extends ServiceImpl<ReplaceDoMapper, ReplaceDo> implements IReplaceDoService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReplaceDoMapper replaceDoMapper;
    @Autowired
    private TradeMapper tradeMapper;
    @Autowired
    private AuditTreeHoleMapper auditTreeHoleMapper;

    //添加代劳信息
    @Transactional
    @Override
    public RespBean addReplaceDo(ReplaceDo replaceDo)  {
        User user = userMapper.selectById(replaceDo.getRdUserId());
        AssertUtil.isTrue(user==null, RespBeanEnum.ReleaseUserIsNotExist);
       AssertUtil.isTrue(StringUtils.isBlank(replaceDo.getContent().trim())||replaceDo.getWay()==null
               ||StringUtils.isBlank(replaceDo.getEndDate().toString()),RespBeanEnum.ParamsIsNull );
        Date now=new Date();
        Date nowAfterOneHour=new Date(now.getTime()+3600000);//当前时间后一个小时,3600000是毫秒
        AssertUtil.isTrue(nowAfterOneHour.after(replaceDo.getEndDate()),RespBeanEnum.EndDateIsError);
       AssertUtil.isTrue(replaceDo.getWay()!=1&&replaceDo.getWay()!=0,RespBeanEnum.WayIsNotExist);//0代拿1代买
        if(replaceDo.getPrice()==null){
            replaceDo.setPrice("待商量");
        }
        replaceDo.setStartDate(new Date());//设置发布时间
        replaceDo.setRdSchoolId(user.getSchoolId());
        replaceDo.setState(0);//默认0待审核,(0审核中、1审核通过；2待接单中，3已被接单,4订单完成)
        AssertUtil.isTrue(replaceDoMapper.insert(replaceDo)!=1,RespBeanEnum.SystemBusy);
        return RespBean.success();
    }

    //获取当前登录用户所在学校的所有的代劳信息列表
    @Override
    public RespBean getAllReplaceDo(ReplaceDoQuery replaceDoQuery) {
        User user = userMapper.selectById(replaceDoQuery.getUserId());
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);
        replaceDoQuery.setSchoolId(user.getSchoolId());
        //准备一个map来返回代劳信息列表和分页信息
        Map<String,Object> map=new HashMap<>();
        //开启分页
        PageHelper.startPage(replaceDoQuery.getPage(),replaceDoQuery.getLimit());
        PageInfo<ReplaceDoReturnVo> pageInfo=new PageInfo<>(replaceDoMapper.queryAllReplaceDo(replaceDoQuery));
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return RespBean.success(map);
    }

    //获取当前需要审核的代劳的数量
    @Override
    public RespBean getNewAudit(String userId) {
        User user = userMapper.selectById(userId);
        if (user.getRole().equals("ordinary")){
            return RespBean.success(null);
        }
        Integer num= replaceDoMapper.getNewAudit(user.getSchoolId());
        return RespBean.success(num);
    }

    //管理员获取所有待审核的代劳列表
    @Override
    public RespBean getAllAudit(String  role,String userId) {
        User user = userMapper.selectById(userId);
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);

        //判断是否有查询的权限
        AssertUtil.isTrue(!role.equals("admin"),RespBeanEnum.InsufficientAuthority);//权限不足

        List<ReplaceDo> auditReplaceDoList= replaceDoMapper.getAllAuditReplaceDo(user.getSchoolId());
        return RespBean.success(auditReplaceDoList);
    }

    //管理员通过代劳ids审核代劳信息
    @Transactional
    @Override
    public RespBean registerReplaceDoByIds(AuditListVo auditListVo, Boolean isAudit, String userId) {
        //判断当前用户的角色是否拥有权限
        User user = userMapper.selectById(userId);
        AssertUtil.isTrue(user==null,RespBeanEnum.UserError);
        AssertUtil.isTrue(!user.getRole().equals("admin"),RespBeanEnum.InsufficientAuthority);
        AssertUtil.isTrue(auditListVo.getCheckedAuditList().isEmpty(),RespBeanEnum.AuditListIsNull);
        AssertUtil.isTrue(isAudit==null,RespBeanEnum.selectIsPass);
        auditListVo.getCheckedAuditList().forEach(item->{
            ReplaceDo replaceDo = replaceDoMapper.selectById(item);
            AssertUtil.isTrue(replaceDo.getState()!=0,RespBeanEnum.RDIsAudited);//-1审核不通过,0审核中、1待接单中(审核通过),2已被接单，3订单完成
           if (isAudit){//表示审核通过
               replaceDo.setState(1);
           }else{//表示审核不通过
               replaceDo.setState(-1);
           }

           AssertUtil.isTrue(replaceDoMapper.updateById(replaceDo)!=1,RespBeanEnum.SystemBusy);
        });

        return RespBean.success();
    }

    //根据指定代劳id删除代劳信息,还有当前操作的用户是管理员才行
    @Transactional
    @Override
    public RespBean deleteReplaceDo(Long id, String userId) {
        User user = userMapper.selectById(userId);
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);
        AssertUtil.isTrue(!user.getRole().equals("admin"),RespBeanEnum.InsufficientAuthority);
        ReplaceDo replaceDo = replaceDoMapper.selectById(id);
        AssertUtil.isTrue(replaceDo==null,RespBeanEnum.RDIsDelete);
        AssertUtil.isTrue(replaceDoMapper.deleteById(id)!=1,RespBeanEnum.SystemBusy);
        return RespBean.success();
    }

    //用户接单
    @Transactional//读提交(isolation = Isolation.READ_COMMITTED)
    @Override
    public RespBean receiveReplaceDo(Trade trade) {
        AssertUtil.isTrue(trade.getReplaceId()==null||StringUtils.isBlank(trade.getTrUserId()) ,RespBeanEnum.ReceiveInfoNotNull);
        User user = userMapper.selectById(trade.getTrUserId());
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);
        ReplaceDo replaceDo = replaceDoMapper.selectById(trade.getReplaceId());
        AssertUtil.isTrue(trade.getTrUserId().equals(replaceDo.getRdUserId()),RespBeanEnum.NotReceiveYourSelfRD);
        AssertUtil.isTrue(replaceDo.getState()==2,RespBeanEnum.RDIsReceived);
        AssertUtil.isTrue(replaceDo.getState()!=1,RespBeanEnum.RDIsNotPass);
        replaceDo.setState(2);
        AssertUtil.isTrue(replaceDoMapper.updateById(replaceDo)!=1,RespBeanEnum.SystemBusy);

        //设置默认值
        trade.setTakingDate(new Date());//接单时间
        trade.setState(0);
        //随机生成订单号
        SnowflakeIdGenerator tradeNo=new SnowflakeIdGenerator(1,1);
        trade.setTradeNo(String.valueOf(tradeNo.nextId()));
        AssertUtil.isTrue(tradeMapper.insert(trade)!=1,RespBeanEnum.SystemBusy);
        return RespBean.success();
    }

    @Override
    public void deleteRDEndDateOver7Day() {

        if (replaceDoMapper.deleteRDEndDateOver7Day()>0){
            System.out.println("定时删除过期RD，时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+",删除成功！");
        }else {
            System.out.println("定时删除过期RD，时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+",暂无RD数据过期！");
        }
        if (auditTreeHoleMapper.deleteNoPassOver()>0){
            System.out.println("定期删除未通过审核的树洞: "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"成功");
        }else {
            System.out.println("定期删除未通过审核的树洞: "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"暂无可删除数据");
        }

    }

    @Override
    public RespBean getRepublishRD(String userId) {
        List<RepublishRDVo>  republishRD= replaceDoMapper.getRepublishRDByUid(userId);
         int num = replaceDoMapper.getRepublishNumByUid(userId);
         Map<String,Object>map=new HashMap<>();
         map.put("data",republishRD);
         map.put("num",num);
        return RespBean.success(map);
    }

}
